//
//  UserLogic.m
//  MyApplication
//
//  Created by 彭凯敏 on 15/7/29.
//  Copyright (c) 2015年 52xiaoluo. All rights reserved.
//

#import "UserLogic.h"

#import "MsgLogic.h"
#import "ViewRoomLogic.h"
#import "head.pb.h"
#import "account.pb.h"
#import "AESCrypt.h"
#import "SecrityLogic.h"
//#import "mainCmd.pb.h"
#import "message.pb.h"
#import "NetEngine.h"
#import "UserModuleManager.h"
/**
 *  Define
 */
#define USERDATA @"USERDATA"

#define SWITCH_SESSION_LOGIN @"login"
#define SWITCH_SESSION_LOGOUT @"logout"
#define SWITCH_SESSION_APPSTART @"appStart"

@implementation UserLogic
{
    Session *session;
}

/**
 *  单例
 */

static UserLogic* _instance = nil;
+(instancetype) shareInstance
{
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        _instance = [[UserLogic alloc] init] ;
    });
    
    return _instance ;
}

-(id) init {
    [self loadSession];
    return self;
}

-(NSString*)getDBName {
    return [[NSString alloc]initWithFormat:@"%llu.db",[self getUserId]];
}

-(NSUserDefaults *)getUserDefault {
    NSString *user_profile = [[NSString alloc]initWithFormat:@"%llu.profile",[self getUserId]];
    return [[NSUserDefaults alloc] initWithSuiteName:user_profile];
}


-(void) loadSession {
    NSData *data = GetNSUserDefaults(USERDATA);
    if (data != nil) {
        Session * newSession = [Session parseFromData:data];
        [self switchSession:newSession :SWITCH_SESSION_APPSTART];
    }
}

-(void)switchSession:(Session *)newSession :(NSString *)reason{
    DLog(@"switchSession %@ reason %@",newSession.description,reason);

    // clear old session
    if (newSession != nil) {
        SetNSUserDefaults(USERDATA, newSession.data);
    } else {
        RemoveNsUserDefaults(USERDATA)
    }
    session = newSession;
    if ([SWITCH_SESSION_LOGIN isEqualToString:reason]) {
        [[UserModuleManager shareInstance] userLogin];
    } else if ([SWITCH_SESSION_APPSTART isEqualToString:reason]) {
        if ([self getUserId] > 0) {
            [[NetEngine shareInstance] enable];
            [[UserModuleManager shareInstance] userLogin];
        }
    } else if ([SWITCH_SESSION_LOGOUT isEqualToString:reason]) {
        [[NetEngine shareInstance] disable];
        [[UserModuleManager shareInstance] userLogout];
        if ([NSThread isMainThread]) {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"gotoLogin" object:nil];
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter]postNotificationName:@"gotoLogin" object:nil];
            });
            
        }
    }
}

-(void) logoutReq {
    
    //    [self switchSession:nil :SWITCH_SESSION_LOGOUT];
    LogoutReqBuilder *builder = [[LogoutReqBuilder alloc]init];
    [builder setKey:session.key];
    
    [self sendRequest:CMD_USER_LOGOUT PBMsg:builder.build];
}

-(void) logout {
    
    [self switchSession:nil :SWITCH_SESSION_LOGOUT];
}


- (UInt64) getUserId {
    if (session == nil)
        return 0;
    else
        return session.user.uin;
}

- (Session *) getSession {
    return session;
}

#pragma mark - request
/**
 *  登录
 */
- (void)loginWithUser:(User *)user
{
    if (session != nil) {
        DLog(@"already has a user %@,clear",session.description);
        RemoveNsUserDefaults(USERDATA)
        session = nil;
    }
    [[NetEngine shareInstance] enable];
    LoginReqBuilder *rb = [[LoginReqBuilder alloc] init];
    rb.user = user;
    rb.deviceToken = self.token;
    [self sendRequest:CMD_USER_LOGIN PBMsg:rb.build];
}

- (void)registWithUser:(User *)user andCode:(NSString *)codeStr
{
    RegisterReqBuilder *rb = [[RegisterReqBuilder alloc] init];
    [rb setUser:user];
    [rb setCode:codeStr];
    
    [self sendRequest:CMD_USER_REG PBMsg:rb.build];
}


#pragma mark - RequestDelegate
- (void)onResult:(Packet *)result req:(Request *)req
{
    NSData *plain =[[SecrityLogic shareInstance] decryptDefault:result.eBody];
    
        if([result.cmd isEqualToString:CMD_USER_REG])
        {
            if (result.ret == 0) {
                RegisterResp *resp = [RegisterResp parseFromData:plain];
                DLog(@"registResult %@",resp.description);
            }
            else  {
                DLog(@"error,%d %@",result.ret,result.error);
            }
            
        }
        else if ([result.cmd isEqualToString:CMD_USER_LOGIN]) {
            
            if (result.ret == 0) {
                LoginResp *loginResp = [LoginResp parseFromData:plain];
                [self switchSession:loginResp.session :SWITCH_SESSION_LOGIN];
                dispatch_sync(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"gotoMP" object:nil];
                    
                });
            }
            else{
                dispatch_sync(dispatch_get_main_queue(), ^{
                    ErrorModel *model = [[ErrorModel alloc]init];
                    
                    model.ret = [NSString stringWithFormat:@"%d",(unsigned int)result.ret];
                    model.error = result.error;
                    
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"LoginError" object:model];
                });
            }
            
            
        }
        else if ([result.cmd isEqualToString:CMD_USER_LOGOUT]) {
            if (result.ret == 0) {
                [self switchSession:nil :SWITCH_SESSION_LOGOUT];
                
                [[NSNotificationCenter defaultCenter]postNotificationName:@"LogoutNoti" object:nil];
            }
            else
            {
                ErrorModel *model = [[ErrorModel alloc]init];
                
                model.ret = [NSString stringWithFormat:@"%d",(unsigned int)result.ret];
                model.error = result.error;
                
                [[NSNotificationCenter defaultCenter]postNotificationName:@"LogoutNoti" object:model];
                
                
            }
            
            
        }
    
}

@end
